﻿using Ay.Framework.WPF;
using Ay.Framework.WPF.Controls;
using Base.BLL;
using Base.DAL;
using MPSystem;
using MPSystem.Models;
using MPSystem.Util;
using MPSystem.Views.YFQ;
using MPSystem.Views.ZCYL;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Visifire.Charts;

namespace ADX.Views
{
    /// <summary>
    /// ZCYLPage.xaml 的交互逻辑
    /// </summary>
    public partial class ZCYLPage_WYYL_History : Page
    {
        //通用类
        Common common = new Common();
        public static ZCYLPage_WYYL_History Me = null;
        public static int cqbh = 0, xdbh = 0;
        public ObservableCollection<ReportWYModel> AllDatas { get; set; } = new ObservableCollection<ReportWYModel>();
        public ObservableCollection<View_DBLC_Active_ROW> AllWarnDatas { get; set; } = new ObservableCollection<View_DBLC_Active_ROW>();
        public DataQuery_WYModel SearchModel { get; set; } = new DataQuery_WYModel();
        int lc = 100;//量程
        int line = 0;
        string lx = "0";//0:离层 1:下沉
        private double UpperLimit = 40;//上限值
        private double LowLimit = 20;//下限值
        private double WarnLimit = 0;
        
        private string ComanpyName = "";
        bool FirstReflash = true;
        bool FirstLoadWarn = true;
        List<Dictionary<string, string>> conditons = new List<Dictionary<string, string>>();
        private string dtStart = "", dtEnd = "", wz = "", channel = "",   minP = "", DW = "MPa", zbhs= "" , IfVisible ="是";
        private int bh = 0;

        private List<string> channel_List = new List<string>()  ;

        private bool _IsBusy = false;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set {  _IsBusy=value ; }
        }
 
        public ZCYLPage_WYYL_History()
        {
            InitializeComponent();
            Loaded += AyPage_Loaded;
            Me = this;
        }
 

        void AyPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= AyPage_Loaded;

            var rcq = ConfigService.GetCQ(true);
            if (rcq.Count() == 0)
            {
                AyMessageBox.ShowError("没有测区！");
                return;
            }
            combcq.ItemsSource = rcq;
            combcq.SelectedIndex = 0;
            //巷道
            var rxd = ConfigService.GetXD(rcq.ElementAt(0).CQBH);
            combxd.ItemsSource = common.LoadCombox_IECobx(rxd);
            if (rxd.Count() > 0) combxd.SelectedIndex = 1;

            ComanpyName = common.GetCompanyName();
            T_CompayName.Text = ComanpyName + "围岩应力历史数据分析曲线图";

        }

        private void LayoutRoot_load(object sender, EventArgs e)
        {
            //syncData();
        }


        void syncData()
        {
            cqbh = AyCommon.ToInt(combcq.SelectedValue);
            xdbh = AyCommon.ToInt(combxd.SelectedValue);
            var cond = WYYLHistory_Condition.Me.Cond;
            if (cond.Count == 0) return;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, ea) =>
            {
                //no direct interaction with the UI is allowed from this method
                AyThread.Instance.RunUI(() =>
                {
                    bh = AyCommon.ToInt(cond["bh"]);
                    dtStart = cond["dtStart"];
                    dtEnd = cond["dtEnd"];
                    int jq= AyCommon.ToInt(cond["jq"]);

                    DataCqylService ds = new DataCqylService();
                    DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd);
                    //db = new DateTime(2018,12,23); de = new DateTime(2018, 12, 24);
                    var r = ds.CurveNormal(cqbh, xdbh,bh, db, de,jq);
                    CreateChartColumn("监测报表", r);
                });
                //CreateChartColumn("测试", strListx, strListy);
            };
            worker.RunWorkerCompleted += (o, ea) =>
            {
                //work has completed. you can now interact with the UI
                busyin1.IsBusy = false;
            };
            //set the IsBusy before you start the thread
            busyin1.IsBusy = true;
            worker.RunWorkerAsync();
        }

        private void btnHquery_Click(object sender, RoutedEventArgs e)
        {
            if (combxd.SelectedIndex == -1 || combxd.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和巷道！");
                return;
            }
            xdbh = int.Parse(combxd.SelectedValue.ToObjectString());
            ShowNavigationWindow("多条件筛选", "/Views/YFQ/WYYLHistory_Condition.xaml", 600, 500);
        }

        
        private void btnquery_Click(object sender, RoutedEventArgs e)
        {
            if (combxd.SelectedIndex == -1 || combxd.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和巷道！");
                return;
            }
            xdbh = int.Parse(combxd.SelectedValue.ToObjectString());
            syncData();
        }        

        /// <summary>/// 弹出层对象/// </summary>

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height){
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing;
                // window.pas += new window.PassValuesHandler(ReceiveValues);
            }
            else
            {
                WYYLHistory_Condition.Me.LoadBH();
            }
            window.ShowDialog();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            WYYLHistory_Condition.Me.UpdateCond();
            window.Hide();
            Me.syncData();
            e.Cancel = true;
        }

        /// <summary>/// 关闭弹出层/// </summary>
        private void CloseNavigationWindow(){
           window.Close();
        }

        private void CloseThis(object sender, CancelEventArgs e)
        {
            window = null;
        }

        private bool isPick = false;
        private void Chart_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!MPSystem.SESSIONS.ShowMenu || chart.Series.Count < 2 || chart.Series[1].DataPoints.Count == 0)
            {
                return;
            }
            ContextMenu menu = new ContextMenu();
            MenuItem menuItem1 = new MenuItem();
            menuItem1.Header = isPick ? "取消标记" : "标记";
            menuItem1.Click += new RoutedEventHandler((s, ee) => {
                isPick = !isPick;
                chart.IndicatorEnabled = isPick;
                if (!isPick)
                {
                    markers.DataPoints.Clear();
                }
            });
            menu.Items.Add(menuItem1);

            MenuItem menuItem2 = new MenuItem();
            menuItem2.Header = "导出标记";
            menuItem2.IsEnabled = markers.DataPoints.Count > 0;
            menuItem2.Click += new RoutedEventHandler((s, ee) => {

                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".txt";
                dlg.Filter = "txt file|*.txt";
                dlg.CheckFileExists = false;
                if (dlg.ShowDialog() == true)
                {
                    //排序
                    List<DataPoint> sorted = markers.DataPoints.ToList();
                    sorted.Sort((x, y) =>
                    {
                        var xs = new List<string>();
                        for (int i = 1; i < chart.Series.Count; i++)
                        {
                            xs.Add(chart.Series[i].LegendText);
                        }
                        int cmp = ((DateTime)x.XValue).CompareTo(y.XValue);
                        if (cmp == 0)
                        {
                            return xs.IndexOf(x.Href.ToString()).CompareTo(xs.IndexOf(y.Href.ToString()));
                        }
                        return cmp;
                    });
                    FileStream fs = new FileStream(dlg.FileName, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.NewLine = Environment.NewLine;
                    DateTime lastDate = DateTime.MinValue;
                    foreach (var dp in sorted)
                    {
                        if (lastDate != (DateTime)dp.XValue)
                        {
                            if (lastDate != DateTime.MinValue)
                            {
                                sw.WriteLine();
                            }
                            sw.WriteLine(((DateTime)dp.XValue).ToString("yyyy-MM-dd HH:mm:ss"));
                            lastDate = (DateTime)dp.XValue;
                        }
                        sw.Write(string.Format("{0}{1} ",dp.YValue, DW));
                    }
                    sw.Flush();
                    sw.Close();
                    AyMessageBox.Show("导出完毕！");
                }
            });
            menu.Items.Add(menuItem2);

            //MenuItem menuItem3 = new MenuItem();
            //menuItem3.Header = "导出所有";
            //menuItem3.Click += new RoutedEventHandler((s, ee) => {

            //    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            //    dlg.DefaultExt = ".txt";
            //    dlg.Filter = "txt file|*.txt";
            //    dlg.CheckFileExists = false;
            //    if (dlg.ShowDialog() == true)
            //    {
            //        FileStream fs = new FileStream(dlg.FileName, FileMode.Create);
            //        StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            //        sw.NewLine = Environment.NewLine;
            //        for (int i = 1; i < chart.Series.Count; i++)
            //        {
            //            var series = chart.Series[i];
            //            sw.WriteLine(series.LegendText);
            //            foreach (var dp in series.DataPoints)
            //            {
            //                sw.Write(string.Format("{0}:{1:f1}{2} ", dp.XValue, dp.YValue,MPa));
            //            }
            //            sw.WriteLine();
            //        }
            //        sw.Flush();
            //        sw.Close();
            //        AyMessageBox.Show("导出完毕！");
            //    }
            //});
            //menu.Items.Add(menuItem3);
            chart.ContextMenu = menu;
        }

        private void Chart_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //0：空 1：辅助标记系列 2开始：数据
            if (!isPick || chart.ToolTips.Count < 2)
            {
                return;
            }
            for (int i = 2; i < chart.ToolTips.Count; i++)
            {
                if (!chart.ToolTips[i].IsVisible || chart.ToolTips[i].Text == "")
                {
                    continue;
                }
                string[] tips = chart.ToolTips[i].Text.Split(new char[] { ',' });
                DataPoint ptClick = new DataPoint();
                ptClick.XValue = DateTime.Parse(tips[0]);
                ptClick.YValue = double.Parse(tips[1].Replace(DW, ""));
                ptClick.Href = chart.Series[i - 1].LegendText;//保存序列日期
                //删除已选定的点
                bool isDel = false;
                for (int j = markers.DataPoints.Count - 1; j >= 0; j--)
                {
                    var pt = markers.DataPoints[j];
                    if (pt.XValue.Equals(ptClick.XValue) && pt.YValue == ptClick.YValue && pt.Href == ptClick.Href)
                    {
                        try { markers.DataPoints.Remove(pt); } catch (Exception ex) { }
                        isDel = true;
                    }
                }
                if (!isDel)
                {
                    //ptClick.MouseLeftButtonDown += new MouseButtonEventHandler((s, ee) => {
                    //    //接收到当前被点击的LengendText的值 
                    //    DataPoint dpoint = s as DataPoint;
                    //});
                    markers.DataPoints.Add(ptClick);
                }
            }
        }

        private DataSeries markers = new DataSeries();
        public void CreateChartColumn(string name, IEnumerable<View_CQYL_Active> rt)
        {
            //创建一个图标
            // Chart chart = new Chart();
            chart.Series.Clear();

            #region 标注功能
            if (FirstReflash)
            {
                markers.ToolTipText = "点击移除此标注";
                markers.XValueType = ChartValueTypes.DateTime;
                markers.RenderAs = RenderAs.Point;
                markers.ShowInLegend = false;
            }
            isPick = false;
            chart.IndicatorEnabled = false;
            markers.DataPoints.Clear();
            chart.Series.Add(markers);
            #endregion

            //设置图标的宽度和高度
            //chart.Width = 580;
            //chart.Height = 380;
            //  chart.Margin = new Thickness(100, 5, 10, 5);
            //是否启用打印和保持图片
            if (FirstReflash)
            {
                chart.ToolBarEnabled = true;

                //设置图标的属性
                chart.ScrollingEnabled = false;//是否启用或禁用滚动
                chart.View3D = false;//3D效果显示

                //创建一个标题的对象
                Title title = new Title();

                //设置标题的名称
                title.Text = Name;
                title.Padding = new Thickness(0, 10, 5, 0);
                //向图标添加标题
                chart.Titles.Add(title);
                //初始化一个新的Axis
                Axis xAxis = new Axis();
                AxisLabels xLabel = new AxisLabels();
                xLabel.Angle = -45;
                xAxis.AxisLabels = xLabel;
                //设置Axis的属性
                //图表的X轴坐标按什么来分类，如时分秒
                xAxis.IntervalType = IntervalTypes.Hours;
                //图表的X轴坐标间隔如2,3,20等，单位为xAxis.IntervalType设置的时分秒。
                //xAxis.Interval = 2;
                //设置X轴的时间显示格式为7-10 11：20           
                xAxis.ValueFormatString = "yyyy-MM-dd HH:mm:ss   ";
                //给图标添加Axis
                chart.AxesX.Add(xAxis);

                FirstReflash = false;
            }
            chart.AxesY.Clear();
            Axis yAxis = new Axis();
            //设置图标中Y轴的最小值永远为0           
            yAxis.AxisMinimum = 0;
            yAxis.AxisMaximum = 30;
            //设置图表中Y轴的后缀          
            yAxis.Suffix = "";
            chart.AxesY.Add(yAxis);

            DataSeries oneDataSeries = new DataSeries();
            oneDataSeries.XValueType = ChartValueTypes.DateTime;
            oneDataSeries.LabelEnabled = false;
            oneDataSeries.LabelText = "#YValue";
            oneDataSeries.LegendText = "应力值";
            oneDataSeries.RenderAs = RenderAs.QuickLine;
            oneDataSeries.LineThickness = 1;
            DataPoint oneDataPoint = null;
            foreach (var d in rt)
            {
                oneDataPoint = new DataPoint();
                oneDataSeries.XValueFormatString = "yyyy-MM-dd HH:mm:ss";
                oneDataSeries.YValueFormatString = "0.0'" + DW + "'";
                oneDataPoint.XValue = d.CQDATETIME;
                oneDataPoint.YValue = d.CQDATA;
                oneDataSeries.DataPoints.Add(oneDataPoint);
            }
            chart.Series.Add(oneDataSeries);
    
            if (FirstLoadWarn)
            {
                TrendLine tl = new TrendLine();
                tl.Value = WarnLimit;
                tl.LineThickness = 1;
                tl.LabelText = "初始预压："+ WarnLimit;
                tl.LineColor = new SolidColorBrush(Colors.LightPink);
                chart.TrendLines.Add(tl);
                FirstLoadWarn = false;
            }
        }

        private void combcq_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combcq.SelectedValue == null) return;
            cqbh = AyCommon.ToInt(combcq.SelectedValue);
            var xdSource = ConfigService.GetXD(cqbh);
            combxd.ItemsSource = common.LoadCombox_IECobx(xdSource);
            if (xdSource.Count() > 0) combxd.SelectedIndex = 1;
        }

        private void Combgzm_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combxd.SelectedValue == null) return;
            xdbh = AyCommon.ToInt(combxd.SelectedValue);
            View_CQYL_INI_CS cs = ConfigService.FindCqyl(cqbh, xdbh);
            if (cs != null)
            {
                WarnLimit = cs.CQCSYY;
                FirstLoadWarn = true;
            }
        }
    }
}
